<?php

class Admin_LoginController extends Zend_Controller_Action {

    private $_debugLogger;
    private $_errorLogger;

    public function preDispatch() {
//        if (Zend_Auth::getInstance()->hasIdentity()) {
//            $this->_forward("index", "dashboard", "admin");
//        }
    }

    public function init() {
        $this->_helper->layout->disableLayout();
        $this->_debugLogger = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
        $this->_errorLogger = Zend_Registry::get(VirtualLabs_Common::ERROR_LOG);
    }

    public function indexAction() {
        
    }

    public function generateAction() {
        $password = $this->getRequest()->getParam("generate");
        echo md5($password);
    }

    public function passwordforgotAction() {
        
    }

    public function logoutAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        Zend_Auth::getInstance()->clearIdentity();
        $this->_forward("index", "login", "admin");
    }

    public function loginAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->_forward("index", "dashboard", "admin");
        }

        $username = $this->getRequest()->getParam('username');
        $password = $this->getRequest()->getParam('password');
        $this->_debugLogger->debug(" [LOGIN]  $username");
        if (trim($username) == "") {
            $this->view->loginError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Authentication error!</div>";
            $this->_forward("index");
        } else {
            $authentication = new VirtualLabs_Auth($username, $password);
            if ($authentication->authenticate()) {
                $this->_forward("index", "dashboard", "admin");
            } else {
                $this->view->loginError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Verifique el nombre de usuario y password!</div>";
                $this->_forward("index");
            }
        }
    }

    public function passwordAction() {
        $username = $this->getRequest()->getParam("username");
        $userDao = new VirtualLabs_Admin_Usuario();
        $userInfo = $userDao->getUsuario(array('nombre', 'email'), array('username' => array('criteria' => '=', 'value' => $username)));
        $this->view->username = $username;
        $this->view->nombre = $userInfo["nombre"];
        $password = $this->getRequest()->getParam("password");

        if (isset($password)) {
            if (strlen(trim($password)) > 0) {
                $code = $this->getRequest()->getParam("code");
                $branch = $this->getRequest()->getParam("branch");
                if (Conexion_Reventa_ClientDataAccess::changeClientPassword($code, $branch, $password) > 0) {
                    $this->_forward("index", "login", "academico");
                } else {
                    $this->view->changeError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Check your password!</div>";
                }
            } else {
                $this->view->changeError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Check your password!</div>";
            }
        }
    }

    public function resetpasswordAction() {
        $userDao = new VirtualLabs_Admin_Usuario();
        try {
            $userDao->resetPassword($this->getRequest()->getParam('username'), $this->getRequest()->getParam('password'));
            $this->_forward('index', 'dashboard', 'admin');
        } catch (Exception $e) {
            throw $e;
        }
    }

    public function loginforgotAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $key = $this->getRequest()->getParam("key");
        $this->_debugLogger->debug('loginforgot action.. ' . $key);
        $this->_debugLogger->debug('[key] : ' . $key);

        if (isset($key)) {
            if (strlen(trim($key)) > 0) {
                $userDao = new VirtualLabs_Admin_Usuario();
                $user = $userDao->loginForgotUsuario($key);

                if ($user) {
                    $generatedPassword = $userDao->generatePassword();
                    $userDao->resetPassword($key, $generatedPassword);
                    $this->_debugLogger->debug('[generatedPassword] : ' . $generatedPassword);
                    if ($generatedPassword) {
// email support password:  AwWmJc]U))UF
                        $config = array('auth' => 'login',
                            'port' => '26',
                            'username' => 'support@pearljamparaguay.com',
                            'password' => 'AwWmJc]U))UF');
                        $tr = new Zend_Mail_Transport_Smtp('mail.pearljamparaguay.com', $config);
                        Zend_Mail::setDefaultTransport($tr);
                        Zend_Mail::setDefaultFrom('support@pearljamparaguay.com', 'Soporte Virtual Labs Manager');
                        Zend_Mail::setDefaultReplyTo('support@pearljamparaguay.com', 'Soporte Virtual Labs Manager');
                        
                        $mail = new Zend_Mail();
                        $mail->addTo($user['email']);
                        $this->_debugLogger->debug('[email] : ' . $user['email']);
                        $mail->setSubject('Solicitud de cambio de password');
                        $msg = utf8_encode("Estimado/a " . $user["nombre"] . ": <br><br>Clic <a href='" .
                                $this->view->baseUrl() . "/admin/login/resetpassword/password/" .
                                $generatedPassword .
                                "/username/" . $user['username'] . "'>aquí</a> para completar el proceso de reinicio de contraseña. <br>"
                                . "Si el enlace no funciona, utilice estos datos para ingresar:
                                        <ul><li>username : {$user['username']}</li><li>password: {$generatedPassword}</li></ul><br><br>Saludos!");
                        $mail->setBodyHtml($msg);
                        $mail->send($tr);
                        $this->_forward('index');
                        $this->view->changeError = "<div class='alert alert-block alert-success fade in' id='value-alert'>Password restablecido. Favor verificar su correo!</div>";
                    } else {
                        $this->view->changeError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Contacte con el administrador!</div>";
                    }
                } else {
                    $this->view->changeError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Contacte con el administrador!</div>";
                }
            } else {
                $this->view->changeError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Verificar su correo!</div>";
            }
        }
    }

}

